import Cos from '@/config/cos';
import { SessionGuard } from '@/guard/session.guard';
import { ResponseBody, ResponseCode } from '@/utils/ResponseCode';
import {
  Controller,
  HttpException,
  HttpStatus,
  Post,
  UploadedFiles,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { extname } from 'path';

@UseGuards(SessionGuard)
@Controller('upload')
export class UploadController {
  @Post('/image')
  // 前端传file，里面是多个文件，
  @UseInterceptors(
    // 最大允许同时上传数量为2，两个已经有点慢了，单个最大5M
    FilesInterceptor('file', 2, {
      limits: {
        fileSize: 1024 * 1024 * 5,
      },
    }),
  )
  async uploadImage(@UploadedFiles() files: Array<Express.Multer.File>) {
    try {
      const imageUrlList = await Promise.all(
        files.map((file) =>
          Cos.putImage(file.buffer, {
            saveDir: 'authority',
            extname: extname(file.originalname),
          }),
        ),
      );
      return new ResponseBody<string[]>({
        message: '上传图片列表成功',
        data: imageUrlList,
      });
    } catch (error) {
      throw new HttpException(
        {
          message: error,
          code: ResponseCode.Fail,
          data: null,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}
